<template>
  <div class="form-container">
    <div class="form-contain">
      <div class="form-title">资源的上传</div>
      <a-form
          id="form"
          :form="form"
          v-bind="formItemLayout"
          @submit="uploadSourceSubmit"
      >
        <a-form-item label="资源名称">
          <a-input
              placeholder="请输入资源名称"
              v-decorator="['resourceName', { rules: [{ required: true, message: '请输入资源名称!' }] }]"
          />
        </a-form-item>
        <a-form-item label="资源类别" has-feedback>
          <a-select
              v-decorator="[
                'resourceCid',
                { rules: [{ required: true, message: '请选择资源类别!' }] },
              ]"
              placeholder="请选择资源类别"
          >
            <a-select-option value="1">
              资料
            </a-select-option>
            <a-select-option value="2">
              课件
            </a-select-option>
            <a-select-option value="3">
              软件
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="资源描述">
          <a-textarea
            v-decorator="['resourceDesc']"
            placeholder="请输入资源描述"
            :auto-size="{ minRows: 4, maxRows: 7 }"
          />
        </a-form-item>

        <a-form-item label="封面图" extra="仅可上传一张">
          <a-upload
            list-type="picture-card"
            :file-list="picList"
            @preview="handlePreviewImg"
            @change="handleChangeImg"
            @customRequest="picRequest"
            :beforeUpload="beforeUploadImg"
            :remove="removeImg"
          >
            <div v-if="picList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>

        <a-form-item label="选择资源">
          <div class="dropbox">
            <a-upload-dragger
              :file-list="fileList"
              name="files"
              :beforeUpload="beforeUpload"
              @customRequest="fileRequest"
              @change="handleChange"
              :multiple="false"
              :remove="removeFile"
            >
              <p class="ant-upload-drag-icon">
                <a-icon type="inbox" />
              </p>
              <p class="ant-upload-text">
                点击或拖拽文件到区域上传文件
              </p>
            </a-upload-dragger>
          </div>
        </a-form-item>

        <a-form-item :wrapper-col="{ span: 12, offset: 10 }">
          <a-button type="primary" html-type="submit">
            提交
          </a-button>
          <a-button :style="{ marginLeft: '60px' }" @click="handleReset">
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </div>

  </div>
</template>

<script>
import {addSource} from "@/api";

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  name: "Upload",
  data:() => ({
    // form: this.$form.createForm(this, { name: 'upload-form' }),
    formItemLayout: {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    },
    previewVisible: false,
    previewImage: '',
    fileList: [],
    picList: []
  }),
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'validate_other' });
  },
  methods: {
    //图片上传
    picRequest(){
      console.log("我是图片上传",this.picList)
    },
    //图片上传之前事件
    beforeUploadImg(file, picList){
      this.picList = [...this.picList, file];
      return new Promise((resolve, reject) => {
        let isLt1M = file.size / 1024 / 1024 <= 20;
        if (!isLt1M) {
          this.$message.error('图片大小不能超过20MB!');
          this.picList = []
          return reject(false);
        }
      })
      console.log('fileList', file,picList)
      return false
    },
    //图片预览
    async handlePreviewImg(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    //文件删除
    removeImg(file) {
      const index = this.picList.indexOf(file);
      const newFileList = this.picList.slice();
      newFileList.splice(index, 1);
      this.picList = newFileList;
    },
    //封面图片上传变化事件
    handleChangeImg(info) {
      if (info.file.status === 'done') {
        this.picList = info.file.originFileObj
      }
    },
    //文件上传
    fileRequest(){
      console.log("我是文件上传",this.fileList)
    },
    //文件上传之前事件
    beforeUpload(file, fileList){
      this.fileList = [...this.fileList, file];
      return new Promise((resolve, reject) => {
        let isLt1M = file.size / 1024 / 1024 <= 20;
        if (!isLt1M) {
          this.$message.error('软件大小不能超过20MB!');
          this.fileList = []
          return reject(false);
        }
      })
      return false
    },
    //上传资源
    uploadSourceSubmit(e) {
      let data;
      e.preventDefault();
      if (this.fileList.length>0 && this.picList.length>0) {
        this.form.validateFields((err, values) => {
          if (!err) {
            const { fileList } = this;
            // const { picList } = this;
            data = this.form.getFieldsValue()
            data.userName = window.localStorage.getItem('userName')
            if(data) {
              let formData = new FormData();
              formData.append("resourceName", data.resourceName);
              formData.append("resourceCid", data.resourceCid);
              formData.append("userName", data.userName)
              formData.append("resourceDesc", data.resourceDesc)
              fileList.forEach(file => {
                formData.append('files', file);
              });
              formData.append('coverImg', this.picList[0]);

              addSource(formData)
                  .then((res) => {
                    if (res.status == 200){
                      this.$message.success('上传资源成功！');
                      this.fileList = []
                      this.picList = []
                      this.handleReset()
                    }else{
                      this.$message.info(res.msg);
                    }
                  })
                  .catch((err) => {
                    this.$message.error(err);
                  })
            }
          }
        });
      } else {
        this.$message.info('封面图与资源不能为空，请重新上传！')
      }

    },
    //文件删除
    removeFile(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    handleCancel() {
      this.previewVisible = false;
    },
    handleChange(info) {
      if (info.file.status === 'done') {
        this.fileList = info.file.originFileObj
      }
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values);
        }
      });
    },
    normFile(e) {
      console.log('Upload event:', e);
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    },
    handleReset() {
      this.form.resetFields();
    },
  },
}
</script>

<style scoped>
  .form-container {
    display: flex;
    justify-content: center;
  }
  .form-contain {
    width: 1000px;
    padding: 0px 30px 30px 30px;
    border-radius: 10px;
    border: 1px solid #5DD5C8;
    margin: 50px 0px;
  }
  .form-title {
    font-size: 20px;
    font-weight: bold;
    text-align: center;
    padding: 20px;
    border-bottom: 1px solid #97f3e9;
  }
  #form {
    margin-top: 30px;
  }
</style>